<template>
  <div>
    <basic-container>
      <div class="el-page-header haruyuki-mb-20">
        <div
          class="el-page-header__left haruyuki-flex-center haruyuki-size-18"
          @click="goBack"
        >
          <i class="el-icon-arrow-left"></i>
          <div class="haruyuki-size-16">返回</div>
        </div>
        <div class="el-page-header__content">库存入库</div>
      </div>
      <div class="haruyuki-flex-x-end haruyuki-mb-20">
        <el-button type="primary" size="small" icon="el-icon-upload2" plain @click="handleImport">批量入库</el-button>
      </div>
      <stock-storage-form v-if="stockForm.rptNo =='19'" :store-form="stockForm" :disabled="serviceForbid" ref="stockStorage"></stock-storage-form>
      <stock-pos-form v-if="stockForm.rptNo =='20'||stockForm.rptNo =='24'" :store-form="stockForm" :disabled="serviceForbid" ref="stockStorage" />
      <div class="haruyuki-flex-center">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleSave">添 加</el-button>
      </div>
      <avue-crud
        :option="option"
        :search.sync="search"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @sort-change="sortChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            @click="handleDelete"
            >删 除
          </el-button>
        </template>
      </avue-crud>
    
      <div class="haruyuki-flex-center haruyuki-mt-20">
        <el-button type="primary" size="small" :disabled="subDis" @click="submitStorage">确认入库</el-button>
        <el-button size="small" @click="goBack">取 消</el-button>
      </div>
      <!-- 导入 -->
      <el-dialog
        title="数据导入"
        append-to-body
        :visible.sync="excelBox"
        v-if="excelBox"
        width="555px"
      >
        <avue-form
          :option="excelOption"
          v-model="excelForm"
          :before-close="handleCloseExcel"
        >
          <template slot="excelFile">
            <el-upload
              ref="upload"
              class="upload-demo"
              drag
              :limit="1"
              :http-request="httpRequest"
              :on-success="onSuccess"
              :on-change="handleChange"
              :on-remove="handleRemove"
              multiple
              :file-list="fileList"
              :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">请上传 .xls,.xlsx 标准格式文件</div>
            </el-upload>
            <div style="display: flex; justify-content: flex-end;">
              <el-button type="primary" @click="uploadSubmit" :disabled="uploadDisabled" v-show="fileList.length">
                确定上传<i class="el-icon-upload2 el-icon--right"></i>
              </el-button>
            </div>
          </template>
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  add,
  queryStoreList,
  getExportTemplate,
  uploadFile,
  getExportTemplatePos
} from "@/api/rb-oem/store/store";
import stockStorageForm from '../components/stock_storage_form.vue';
import { downloadFileExcel } from "@/util/util";
import { mapGetters } from 'vuex'

import stockPosForm from '../components/stock_pos_form.vue';

let storeId = 1;
export default {
  data() {
    return {
      subDis:false,
      stockForm: {
        userNo: '',
        userNoServe: '',
        userNoServeName: '',
        belongTo: '',
        aisleCode: '',
        rptNo: '',
        rpsNo: '',
        rpmNo: '',
        rsSn: '',
        startSn: '',
        endSn: '',
        activeType: '',
        cardCode: '',
        qrCode: '',
        yxToken: '',
        businessType: '',
        cardFee:'',
        flowFee:''
      },
      serviceForbid: false,
      form: {},
      query: {},
      search: {},
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
      },
      loading: false,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option:{},
      optionBase: {
        //height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        search: false,
        // columnBtn: false,
        addBtn: false,
        editBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "服务商编号",
            prop: "userNoServe",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "服务商名称",
            prop: "userNoServeName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备归属",
            // prop: "belongTo",
            prop: "belongToName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "通道名称",
            prop: "aisleName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备类型",
            // prop: "rptNo",
            prop: "rptName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备品牌",
            // prop: "rpsNo",
            prop: "rpsName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备型号",
            // prop: "rpmNo",
            prop: "rpmName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备编号",
            prop: "rsSn",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "二维码编号",
            prop: "qrCode",
            slot: true,
            display: false,
            overHidden: true,
          },
          // {
          //   label: "活动类型",
          //   prop: "activeType",
          //   slot: true,
          //   display: false,
          //   overHidden: true,
          // },
          {
            label: "活动类型",
            prop: "activeName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "音响密钥",
            prop: "yxToken",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "物联网卡编号",
            prop: "cardCode",
            slot: true,
            display: false,
            overHidden: true,
          },
        ],
      },
      optionPos: {
        //height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        search: false,
        // columnBtn: false,
        addBtn: false,
        editBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "服务商编号",
            prop: "userNoServe",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "服务商名称",
            prop: "userNoServeName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备归属",
            // prop: "belongTo",
            prop: "belongToName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "通道名称",
            prop: "aisleName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "业务类型",
            prop: "businessType",
            // slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "业务类型名称",
            prop: "businessTypeName",
            // slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备类型",
            // prop: "rptNo",
            prop: "rptName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备品牌",
            // prop: "rpsNo",
            prop: "rpsName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备型号",
            // prop: "rpmNo",
            prop: "rpmName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备编号",
            prop: "rsSn",
            slot: true,
            display: false,
            overHidden: true,
          },
          // {
          //   label: "活动类型",
          //   prop: "activeType",
          //   slot: true,
          //   display: false,
          //   overHidden: true,
          // },
          {
            label: "活动类型",
            prop: "activeName",
            slot: true,
            display: false,
            overHidden: true
          },
          {
            label: "流量卡金额",
            prop: "simAmount",
            overHidden: true
          },
          {
            label: "预设刷卡费(%)",
            prop: "cardFee",
            overHidden: true
          },
          {
            label: "预设通讯费(元)",
            prop: "flowFee",
            overHidden: true
          },
        ],
      },
      data: [],
      awaitData: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "服务商",
            prop: "userNo",
            type: "select",
            span: 24,
            remote: true,
            filterable: true,
            clearable: true,
            props: {
              label: "serviceName",
              value: "serviceNo",
              desc: "serviceNo"
            },
            dicUrl: "/api/rb-oem/oem/serviceInfo/service_info/list?current=1&size=10&serviceAuditStatus=2&isSelectDirect=1&serviceName={{key}}",
            dicFormatter:(data)=>{
              return data.data.records
            }
            // change: ({value}) => {
            //   if (value) {
            //     const column = this.findObject(this.excelOption.column, "excelFile");
            //     column.data.userNo = value;
            //   } else {
            //     const column = this.findObject(this.excelOption.column, "excelFile");
            //     column.data.userNo = '';
            //   }
            // }
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              url:'link',
              name:'originalName',
              res: "data",
            },
            data: {
              userNo: ''
            },
            headers: {
              "Content-Type": "multipart/form-data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/store/store/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ]
      },
      rptNo:"",//页面传参 设备类型
      uploadDisabled:false,
      fileList:[]
    };
  },
  components: {
    stockStorageForm,
    stockPosForm
  },
  computed: {
    ...mapGetters(['tag', 'userInfo', 'permission']),
  },
  watch: {
    data(row) {
      if (row.length == 0) this.serviceForbid = false;
    }
  },
  created() {
    this.rptNoTypeShow();//根据 设备编号 显示
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    uploadSubmit(){
      this.$refs.upload.submit();
    },
    /* 关闭弹框 */
    handleCloseExcel(done){
      this.excelForm = {};
      this.excelForm.userNo = '';
      this.fileList =[];
      done();
    },
    /* 批量文件上传 */
    httpRequest(option){
      this.uploadDisabled = true ;
      uploadFile(option.file, option.file.name,this.excelForm.userNo).then((res) => {
        this.uploadDisabled = false ;
        this.$message({ type: "success", message: res.data.msg });
        this.refreshChange();
      },() =>{
        this.uploadDisabled = false ;
      })
    },
    /* 文件上传后 */
    // uploadAfter(res, done) {
    //   console.log('--------',res)
    //   if (res) {
    //   }
    //   this.refreshChange();
    //   done();
    // },
    /**
     * @desc 根据 设备编号 显示
     * */
    rptNoTypeShow(){
      /**
       * @desc rptNo 设备类型 默认值 19 音响 | 20 传统POS ||24 智能POS
       * */
      if(this.$route.query.rptNo){
        this.stockForm.rptNo = this.$route.query.rptNo;
        this.rptNo = this.$route.query.rptNo;
        if(this.stockForm.rptNo =='20'||this.stockForm.rptNo =='24'){
          this.option = this.optionPos;
        }else{
          this.option = this.optionBase;
        }
      }
    },
    /**
     * @func 提交入库
     * @desc 提交入库
     * */
    submitStorage() {
      if (this.awaitData.length > 0) {
        this.subDis = true;
        add({dto:this.awaitData}).then(
          () => {
            // this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "入库成功!",
            });

            this.handleCloseTag();
            // this.goBack();
          },
          (error) => {
            window.console.log(error);
            this.subDis = false;
          }
        );
      } else {
        this.$message({
          type: "warning",
          message: "请添加入库后再操作!",
        });
      }
    },
    /**
     * @func 添加待入库
     * @desc 添加至待入库列表 可批量添加
     * */
    handleSave() {
      this.$refs["stockStorage"].$refs["storeForm"].validate((valid) => {
        if (valid) {
          queryStoreList(this.stockForm).then(
            (res) => {
              let storeData = res.data.data;
              if (this.data.length > 0) {
                // 首先构造Object
                // reduce  初始值（或者上一次回调函数的返回值），当前元素值，当前索引，调用 reduce 的数组。
                const idSet = this.data.reduce((acc, v) => {
                    acc[v.rsSn] = true;
                    return acc;
                }, {});
                let result = [];

                if(this.rptNo != '20'&&this.rptNo != '24'){
                  // 设备类型 非 传统POS||智能POS
                  const idQrCode = this.data.reduce((acc, v) => {
                      acc[v.qrCode] = true;
                      return acc;
                  }, {});
                  //去重后的result
                  result = storeData.filter(v => !idSet[v.rsSn] && !idQrCode[v.qrCode]);
                }else{
                  // 设备类型
                  result = storeData.filter(v => !idSet[v.rsSn]);
                  
                }
                
                if (result.length > 0) {
                  for (let i = 0; i < result.length; i++) {
                    this.awaitData.unshift({id: storeId++, ...result[i]});
                  }
                  this.serviceForbid = true;
                } else {
                  if(this.rptNo != '20'&&this.rptNo != '24'){
                    // 非 传统POS | 智能POS
                    this.$message({
                      type: "warning",
                      message: "所输入的设备编号、二维码编号不能相同!",
                    });
                  }else{
                    this.$message({
                      type: "warning",
                      message: "所输入的设备编号不能相同!",
                    });
                  }
                }
                // console.log(result, 'result');
              } else {
                for (let i = 0; i < storeData.length; i++) {
                  this.awaitData.unshift({id: storeId++, ...storeData[i]});
                }
                this.serviceForbid = true;
              }
              this.onLoad();
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // return remove(this.ids);
          for (let k = 0; k < this.selectionList.length; k++) {
            this.data.splice(
                this.data.findIndex(
                  item => item.id === this.selectionList[k].id
                ),
                1
            );
          }
        })
        .then(() => {
          // this.onLoad();
          this.awaitData = this.data;
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {
      if(this.rptNo == '20' || this.rptNo == '24'){
        getExportTemplatePos().then((res) => {
          downloadFileExcel(res);
        });
      }else{
        getExportTemplate().then((res) => {
          downloadFileExcel(res);
        });
      }
    },
    refreshChange() {
      this.excelBox = false;
      this.excelForm = {};
      this.excelForm.userNo = '';
      this.fileList =[];
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // return remove(row.id);
          this.data.splice(row.$index, 1);
          this.awaitData = this.data;
        })
        .then(() => {
          // this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    onLoad() {
      this.loading = true;
      if (this.awaitData.length > 0) {
        //awaitData为全部数据，data是目前表格绑定的数据
        this.data = this.awaitData.slice(
          (this.page.currentPage - 1) * this.page.pageSize,
          this.page.currentPage * this.page.pageSize
        );
        this.page.total = this.awaitData.length;
      }
      this.loading = false;
    },
    // 关闭当前tag，并跳转
    handleCloseTag() {
      this.$store.commit('DEL_TAG', this.tag)
      // if()
      this.$router.push({
        path: '/rb-oem/store/store',
        params: {
          id: 1,
        },
      })
    },
    /**
     * @func 返回页面
     * @desc 返回页面 goBack
     * */
    goBack() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    },
  }
};
</script>

<style lang="scss" scoped>
</style>